package redislock;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @Description 扣库存案例模拟分布式锁问题
 * @Date 2020/7/14 10:28
 * @Author taojiangbing
 */
public class TestRedissonLock {

    private static RedisTemplate redisTemplate;

    private static Redisson redisson;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RedisConfig.class);
        redisTemplate = context.getBean(RedisTemplate.class);
        redisson = context.getBean(Redisson.class);

        for (int i = 0; i < 15; i++) {
            new Thread(() -> {
                deductStock();
            }, "Thread-" + i).start();
        }
    }

    private static void deductStock() {
        String lockKey = "product_001";
        //获取锁
        RLock redissonLock = redisson.getLock(lockKey);
        try {
            // 加锁，实现锁续命功能
            redissonLock.lock();
            int stock = Integer.parseInt(redisTemplate.opsForValue().get("stock").toString());
            if (stock > 0) {
                int realStock = stock - 1;
                redisTemplate.opsForValue().set("stock", realStock + "");
            } else {
                System.out.println(Thread.currentThread().getName() + " 扣减失败，库存不足");
            }
        } finally {
            redissonLock.unlock();
        }
    }
}
